<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Models\Usersdomain;
use App\Models\Domainlist;
use App\Models\Memberorder;
use App\Models\Users;
use App\Services\OutputService;
use App\Services\MiniappService;
use App\Services\PayService;
use Exception,Log,Config;

class DomainController extends Controller
{
    public function domainList(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("非法请求,请稍后重试！");
        $userDomains = Usersdomain::userDomainList($request->openid);
        return OutputService::success("SUCCESS",["userDomains"=>$userDomains]);
    }

    public function saleDomain(Request $request)
    {
        $domainLists = Domainlist::saleDomainList();
        return OutputService::success("SUCCESS",["domainLists"=>$domainLists]);
    }

    public function domainBuy(Request $request)
    {
        $openid = $request->openid;
        $domain = $request->domain;
        $year = $request->year;
        $platefrom = $request->platefrom;
        $status = $request->status;
        $appid = $request->appid;
        if (empty($domain)) return OutputService::error("非法请求,请稍后重试！");
        $domainDetial = Domainlist::domainDetial($domain);
        if (empty($domainDetial)) return OutputService::error("租用的域名不存在！");
        if ($domainDetial->status != 1) return OutputService::error("域名已出租,请选择其他域名!");
        $price = 0.1*$year;
        // $price = 100*$year;
        $title = "域名租用(".$year."年)";
        $out_trade_no = md5($openid.time().rand("10000","99999"));
        Memberorder::addOrder($openid,$out_trade_no,$title,1,$year,$price,2,$appid);
        if ($request->platefrom == "app") {
            $result = PayService::getPayParams("alipay","app",$title,$out_trade_no,$price,$openid,$domain);
        } else {
            $result = PayService::getPayParams("wechat","mini",$title,$out_trade_no,$price,$openid,$domain);
        }
        return OutputService::success("SUCCESS",["result"=>$result]);
    }

    public function domainActive(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("非法请求,请稍后重试！");
        if (empty($request->domain)) return OutputService::error("非法请求,请稍后重试！");
        Usersdomain::domainListActive($request->openid);
        Usersdomain::domainSetActive($request->openid,$request->domain);
        $defaultDomain = Usersdomain::userDefaultDomain($request->openid);
        if (empty($defaultDomain)) {
            $defaultDomain = Usersdomain::userDomain($request->openid);
        }
        if (!empty($defaultDomain)) {
            Users::setUserDomain($request->openid,$defaultDomain->domain);
        }
        return OutputService::success("SUCCESS");
    }

}